"""
40Seas 支付 API
提供前端支付界面所需的后端接口
"""

import frappe
from frappe import _
from .utils.Pay400 import Pay400Client, Currency

@frappe.whitelist()
def create_payment_intent(buyer_id, amount, currency="USD", metadata=None):
    """
    创建支付意图
    
    Args:
        buyer_id (str): 买家ID
        amount (float): 支付金额
        currency (str): 货币类型
        metadata (dict): 元数据
    
    Returns:
        dict: 支付意图信息
    """
    try:
        # 初始化40Seas客户端
        client = Pay400Client()
        
        # 创建结账表单
        checkout = client.create_checkout(
            buyer_id=buyer_id,
            amount=float(amount),
            currency=currency,
            metadata=metadata or {}
        )
        
        checkout_id = checkout.get('id')
        if not checkout_id:
            return {
                "success": False,
                "error": "创建结账表单失败"
            }
        
        # 创建支付意图
        intent = client.create_payment_intent(checkout_id)
        
        payment_token = intent.get('token')
        payment_url = intent.get('url')
        
        if not payment_token:
            return {
                "success": False,
                "error": "创建支付意图失败"
            }
        
        # 记录支付信息到数据库
        payment_record = frappe.get_doc({
            "doctype": "40Seas Payment",  # 您配置的 DocType 名称
            "checkout_id": checkout_id,
            "buyer_id": buyer_id,
            "amount": float(amount),
            "currency": currency,
            "payment_token": payment_token,
            "payment_url": payment_url,
            "status": "pending",
            "notification_status": "pending",  # 通知状态
            "metadata": frappe.as_json(metadata or {})
        })
        payment_record.insert(ignore_permissions=True)
        
        return {
            "success": True,
            "data": {
                "checkout_id": checkout_id,
                "payment_token": payment_token,
                "payment_url": payment_url,
                "amount": float(amount),
                "currency": currency
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 创建支付意图失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def handle_payment_success(checkout_id, payment_data):
    """
    处理支付成功
    
    Args:
        checkout_id (str): 结账ID
        payment_data (dict): 支付数据
    
    Returns:
        dict: 处理结果
    """
    try:
        # 查找支付记录
        payment_record = frappe.get_value(
            "40Seas Payment",
            {"checkout_id": checkout_id},
            "name"
        )
        
        if not payment_record:
            return {
                "success": False,
                "error": "支付记录不存在"
            }
        
        # 更新支付记录
        doc = frappe.get_doc("40Seas Payment", payment_record)
        doc.status = "paid"
        doc.notification_status = "sent"  # 更新通知状态
        doc.payment_data = frappe.as_json(payment_data)
        doc.paid_amount = payment_data.get('amount', 0)
        doc.total_fee = payment_data.get('totalFee', 0)
        doc.total_amount = payment_data.get('total', 0)
        doc.payment_option = frappe.as_json(payment_data.get('paymentOption', {}))
        doc.due_date = payment_data.get('dueDate')
        doc.save(ignore_permissions=True)
        
        # 更新用户账户余额（这里需要根据实际业务逻辑调整）
        buyer_id = doc.buyer_id
        amount = doc.amount
        
        # 示例：更新用户余额
        # user_balance = frappe.get_value("User Balance", {"user": buyer_id}, "balance") or 0
        # new_balance = user_balance + amount
        # frappe.set_value("User Balance", {"user": buyer_id}, "balance", new_balance)
        
        # 发送通知
        frappe.publish_realtime(
            "payment_success",
            {
                "checkout_id": checkout_id,
                "amount": amount,
                "currency": doc.currency
            },
            user=frappe.session.user
        )
        
        return {
            "success": True,
            "message": "支付处理成功"
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 处理支付成功失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def get_payment_status(checkout_id):
    """
    获取支付状态
    
    Args:
        checkout_id (str): 结账ID
    
    Returns:
        dict: 支付状态信息
    """
    try:
        # 从40Seas API获取状态
        client = Pay400Client()
        status = client.get_checkout_status(checkout_id)
        
        # 从数据库获取记录
        payment_record = frappe.get_value(
            "40Seas Payment",
            {"checkout_id": checkout_id},
            ["status", "amount", "currency", "buyer_id"],
            as_dict=True
        )
        
        return {
            "success": True,
            "data": {
                "checkout_id": checkout_id,
                "status": status.get('status', 'unknown'),
                "amount": payment_record.get('amount', 0),
                "currency": payment_record.get('currency', 'USD'),
                "buyer_id": payment_record.get('buyer_id', ''),
                "api_status": status
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 获取支付状态失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def create_buyer_for_payment(email, display_name=None, country="US"):
    """
    为支付创建买家
    
    Args:
        email (str): 邮箱
        display_name (str): 显示名称
        country (str): 国家代码
    
    Returns:
        dict: 买家信息
    """
    try:
        client = Pay400Client()
        
        # 先检查是否已存在买家
        buyers = client.get_buyers()
        existing_buyers = buyers.get('results', [])
        
        for buyer in existing_buyers:
            if buyer.get('email') == email:
                return {
                    "success": True,
                    "data": {
                        "buyer_id": buyer.get('id'),
                        "email": buyer.get('email'),
                        "display_name": buyer.get('displayName'),
                        "existing": True
                    }
                }
        
        # 创建新买家
        buyer = client.create_buyer(
            display_name=display_name or email.split('@')[0],
            address={"country": country},
            email=email,
            identification={"type": "ein"}
        )
        
        return {
            "success": True,
            "data": {
                "buyer_id": buyer.get('id'),
                "email": buyer.get('email'),
                "display_name": buyer.get('displayName'),
                "existing": False
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 创建买家失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def webhook_handler():
    """
    处理40Seas webhook
    """
    try:
        # 获取webhook数据
        webhook_data = frappe.request.get_json()
        
        if not webhook_data:
            return {"status": "error", "message": "No data received"}
        
        event_type = webhook_data.get('type')
        checkout_id = webhook_data.get('data', {}).get('id')
        
        frappe.logger().info(f"[40Seas Webhook] 收到事件: {event_type}, 结账ID: {checkout_id}")
        
        if event_type == "checkout.paid":
            # 支付成功
            handle_payment_success(checkout_id, webhook_data.get('data', {}))
        elif event_type == "checkout.failed":
            # 支付失败
            frappe.logger().warning(f"[40Seas Webhook] 支付失败: {checkout_id}")
        elif event_type == "checkout.canceled":
            # 支付取消
            frappe.logger().info(f"[40Seas Webhook] 支付取消: {checkout_id}")
        
        return {"status": "success"}
        
    except Exception as e:
        frappe.logger().error(f"[40Seas Webhook] 处理失败: {str(e)}")
        return {"status": "error", "message": str(e)}

# ==================== DocType CRUD 接口 ====================

@frappe.whitelist()
def get_payment_list(filters=None, limit=20, offset=0):
    """
    获取支付记录列表
    
    Args:
        filters (dict): 过滤条件
        limit (int): 每页数量
        offset (int): 偏移量
    
    Returns:
        dict: 支付记录列表
    """
    try:
        # 构建查询条件
        where_conditions = []
        if filters:
            if filters.get('status'):
                where_conditions.append(f"status = '{filters['status']}'")
            if filters.get('notification_status'):
                where_conditions.append(f"notification_status = '{filters['notification_status']}'")
            if filters.get('buyer_id'):
                where_conditions.append(f"buyer_id = '{filters['buyer_id']}'")
            if filters.get('date_from'):
                where_conditions.append(f"creation >= '{filters['date_from']}'")
            if filters.get('date_to'):
                where_conditions.append(f"creation <= '{filters['date_to']}'")
        
        where_clause = " AND ".join(where_conditions) if where_conditions else "1=1"
        
        # 查询数据
        payments = frappe.db.sql(f"""
            SELECT 
                name, checkout_id, buyer_id, amount, currency, 
                status, notification_status, payment_token, payment_url,
                paid_amount, total_fee, total_amount, due_date,
                creation, modified
            FROM `tab40Seas Payment`
            WHERE {where_clause}
            ORDER BY creation DESC
            LIMIT {limit} OFFSET {offset}
        """, as_dict=True)
        
        # 获取总数
        total = frappe.db.sql(f"""
            SELECT COUNT(*) as total
            FROM `tab40Seas Payment`
            WHERE {where_clause}
        """, as_dict=True)[0].total
        
        return {
            "success": True,
            "data": {
                "payments": payments,
                "total": total,
                "limit": limit,
                "offset": offset
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 获取支付列表失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def get_payment_detail(payment_id):
    """
    获取支付记录详情
    
    Args:
        payment_id (str): 支付记录ID
    
    Returns:
        dict: 支付记录详情
    """
    try:
        doc = frappe.get_doc("40Seas Payment", payment_id)
        
        return {
            "success": True,
            "data": {
                "name": doc.name,
                "checkout_id": doc.checkout_id,
                "buyer_id": doc.buyer_id,
                "amount": doc.amount,
                "currency": doc.currency,
                "status": doc.status,
                "notification_status": doc.notification_status,
                "payment_token": doc.payment_token,
                "payment_url": doc.payment_url,
                "paid_amount": doc.paid_amount,
                "total_fee": doc.total_fee,
                "total_amount": doc.total_amount,
                "payment_option": doc.payment_option,
                "due_date": doc.due_date,
                "metadata": doc.metadata,
                "payment_data": doc.payment_data,
                "creation": doc.creation,
                "modified": doc.modified
            }
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 获取支付详情失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def update_payment_status(payment_id, status, notification_status=None):
    """
    更新支付状态
    
    Args:
        payment_id (str): 支付记录ID
        status (str): 支付状态
        notification_status (str): 通知状态
    
    Returns:
        dict: 更新结果
    """
    try:
        doc = frappe.get_doc("40Seas Payment", payment_id)
        doc.status = status
        
        if notification_status:
            doc.notification_status = notification_status
        
        doc.save(ignore_permissions=True)
        
        return {
            "success": True,
            "message": "状态更新成功"
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 更新支付状态失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def delete_payment(payment_id):
    """
    删除支付记录
    
    Args:
        payment_id (str): 支付记录ID
    
    Returns:
        dict: 删除结果
    """
    try:
        frappe.delete_doc("40Seas Payment", payment_id, ignore_permissions=True)
        
        return {
            "success": True,
            "message": "支付记录删除成功"
        }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 删除支付记录失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }

@frappe.whitelist()
def retry_payment(payment_id):
    """
    重试支付（重新创建支付意图）
    
    Args:
        payment_id (str): 支付记录ID
    
    Returns:
        dict: 重试结果
    """
    try:
        doc = frappe.get_doc("40Seas Payment", payment_id)
        
        if doc.status == "paid":
            return {
                "success": False,
                "error": "支付已完成，无需重试"
            }
        
        # 重新创建支付意图
        client = Pay400Client()
        intent = client.create_payment_intent(doc.checkout_id)
        
        payment_token = intent.get('token')
        payment_url = intent.get('url')
        
        if payment_token:
            doc.payment_token = payment_token
            doc.payment_url = payment_url
            doc.status = "pending"
            doc.notification_status = "pending"
            doc.save(ignore_permissions=True)
            
            return {
                "success": True,
                "data": {
                    "payment_token": payment_token,
                    "payment_url": payment_url
                },
                "message": "支付重试成功"
            }
        else:
            return {
                "success": False,
                "error": "重新创建支付意图失败"
            }
        
    except Exception as e:
        frappe.logger().error(f"[40Seas支付] 重试支付失败: {str(e)}")
        return {
            "success": False,
            "error": str(e)
        }
